import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { constantRoutes } from '@/router'
const state = {
  token: getToken(), // 缓存读取初始值
  userInfo: {}, // 用户个信息
  roles: [],
  routes: constantRoutes
}
const mutations = {
  setToken(state, token) {
    state.token = token
    // 并且把token存入缓存
    setToken(token)
  },
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  },
  removeToken(state) {
    // 清除state 的token
    state.token = null
    // 清除缓存token
    removeToken()
  }
}
const actions = {
  async login(context, data) {
    // 发起接口请求loginApi(data) return token  即let token = loginApi(data)
    const res = await login(data)
    // console.log(res.data.token)
    context.commit('setToken', res.data.token)
  },
  // 获取用户信息/基本资料
  async getInfo(context) {
    const data = await getInfo()
    // console.log(data.data)
    context.commit('setUserInfo', data.data)
    // return data
  },
  // user logout
  async logout(context) {
    await logout()
    context.commit('setUserInfo', {}) // 清楚用户个人信息
    context.commit('removeToken') // 清空token
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
